<?php

namespace app\common\model\auth;

use app\common\model\BaseModel;

class AuthRoleModel extends BaseModel
{
    protected $table = 't_auth_role';

    //删除校验关联关系表是否存在关联数据
    protected $checkDelJoinTable = [
        't_auth_admin|管理员' => 'FIND_IN_SET(%s, role_ids)',
    ];

    const STATUS_OPEN = 1;
    const STATUS_CLOSE = 2;
    public $status = [
        self::STATUS_OPEN => '开启',
        self::STATUS_CLOSE => '关闭'
    ];

    /**
     * 删除角色
     * @param string $roleIds
     * @return bool
     */
    public function delRole($roleIds)
    {
        $errorMsg = [];
        $this->startTrans();
        try {
            $roleIds = explode(',', $roleIds);
            $data = $this->whereIn('id', $roleIds)->select()->column(null, 'id');
            foreach ($roleIds as $k => $v) {
                $num = $k + 1;
                $info = $data[$v] ?? [];
                if (empty($info)) {
                    $errorMsg[] = "第{$num}个角色信息不存在或已删除";
                    continue;
                }

                if ($this->checkDelIsExistJoinData($info['id'])) {
                    $errorMsg[] = "第{$num}个角色" . $this->getError();
                }
            }

            if (empty($errorMsg)) {
                $this->whereIn('id', array_column($data, 'id'))->delete();
            }

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            return $this->setError($e->getMessage());
        }

        if (!empty($errorMsg)) {
            return $this->setError($errorMsg);
        }

        return true;
    }

}